package org.com.java_chatroom.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.com.java_chatroom.model.User;
import org.com.java_chatroom.model.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserAPI {
    @Autowired
    UserMapper userMapper;
    //用户注册:
    @ResponseBody
    @RequestMapping("/register")
    public Object register(String username, String password){
        User user = null;
        try{
            user = new User();
            user.setUsername(username);
            user.setPassword(password);
            int n = userMapper.insertUser(user);
            System.out.println("[UserAPI] register n:"+n);
            user.setPassword("");
        }catch (DuplicateKeyException e){
            //当insert失败时,会抛出DuplicateKeyException异常,就需要返回空的User对象
            user = new User();
            System.out.println("[UserAPI] 用户注册失败!user:"+user );
        }
        return user;
    }

    //用户登录:
    @ResponseBody
    @RequestMapping("/login")
    public Object login(String username, String password, HttpServletRequest req){
        User user = userMapper.selectByName(username);
        if(user==null || !user.getPassword().equals(password)){
            System.out.println("[UserAPI] login:用户名或密码有误");
            return new User();
        }
        //登录成功,创建会话
        //参数设为true,不存在时:创建会话
        HttpSession session = req.getSession(true);
        session.setAttribute("user",user);
        user.setPassword("");
        System.out.println("[UserAPI] 用户登录成功 username:"+username);
        return user;
    }
    //获取用户信息:
    @RequestMapping("/userinfo")
    @ResponseBody
    public Object getUserInfo(HttpServletRequest req){
        HttpSession session = req.getSession(false);
        if(session==null){
            System.out.println("[UserAPI] getUserInfo 未获取到session对象");
            return new User();
        }
        User user = (User) session.getAttribute("user");
        if(user==null){
            //当前用户尚未登录:
            System.out.println("[UserAPI] getUserInfo: 未获取到user对象");
            return new User();
        }
        user.setPassword("");
        return user;
    }
}
